<template>
  <view class="list-page">
    <!-- nav -->
    <tui-navigation-bar :isOpacity="false" color="#333" class="nav">
      <view class="nav-content">
        <view class="left">
          <tui-icon
            name="arrowleft"
            color="#333"
            size="30"
            unit="px"
            @click="back"
          />
        </view>
        <view class="center">
          <view class="title">{{ title }}</view>
        </view>
        <view class="right" @click="clear">
          <tui-icon
            name="search"
            color="#333"
            size="25"
            unit="px"
            @click="toSearch"
          />
        </view>
      </view>
    </tui-navigation-bar>
    <!-- 悬浮添加按钮 -->
    <tui-fab
      @click="showUpload = true"
      bgColor="#198fff"
      :width="50"
      :height="50"
      :bottom="addBtnBottom"
      :right="16"
      :zIndex="9981"
      :maskZIndex="9980"
    ></tui-fab>
    <view class="content">
      <!-- menu -->
      <view class="header-content">
        <view class="left" @click="showSort = true">
          <tui-icon
            name="todown"
            color="#666"
            size="16"
            unit="px"
            class="r"
            v-show="searchForm.order == 'desc'"
          />
          <tui-icon
            name="top"
            color="#666"
            size="16"
            unit="px"
            class="r"
            v-show="searchForm.order == 'asc'"
          />
          <text class="r">{{ sortTitle }}</text>
          <tui-icon name="arrowdown" color="#666" size="16" unit="px" />
        </view>
        <view class="right">
          <view
            class="iconfont icon-table"
            v-show="listView"
            @click="handleView"
          />
          <view
            class="iconfont icon-unorderedlist"
            v-show="!listView"
            @click="handleView"
          />
        </view>
      </view>
      <!-- sort -->
      <tui-bottom-popup
        :show="showSort"
        :radius="false"
        @close="showSort = false"
        :zIndex="9999"
        :maskZIndex="9998"
      >
        <view class="sort-content">
          <tui-list-view
            unlined="bottom"
            color="#222"
            title="排序"
            :size="17"
            fontWeight="500"
          >
            <tui-list-cell
              :size="16"
              :class="{ seleted: searchForm.sort == 'updateTime' }"
              @click="changeSort('updateTime', '按修改时间')"
              >按修改时间
              <tui-icon
                name="todown"
                size="17"
                unit="px"
                class="l"
                :color="searchForm.sort == 'updateTime' ? '#198fff' : ''"
                v-show="
                  searchForm.order == 'desc' && searchForm.sort == 'updateTime'
                "
              />
              <tui-icon
                name="top"
                size="16"
                unit="px"
                class="l"
                :color="searchForm.sort == 'updateTime' ? '#198fff' : ''"
                v-show="
                  searchForm.order == 'asc' && searchForm.sort == 'updateTime'
                "
              />
            </tui-list-cell>
            <tui-list-cell
              :size="16"
              :class="{ seleted: searchForm.sort == 'createTime' }"
              @click="changeSort('createTime', '按创建时间')"
              >按创建时间
              <tui-icon
                name="todown"
                size="17"
                unit="px"
                class="l"
                :color="searchForm.sort == 'createTime' ? '#198fff' : ''"
                v-show="
                  searchForm.order == 'desc' && searchForm.sort == 'createTime'
                "
              />
              <tui-icon
                name="top"
                size="16"
                unit="px"
                class="l"
                :color="searchForm.sortort == 'createTime' ? '#198fff' : ''"
                v-show="
                  searchForm.order == 'asc' && searchForm.sort == 'createTime'
                "
              />
            </tui-list-cell>
            <tui-list-cell
              :size="16"
              unlined
              :class="{ seleted: searchForm.sort == 'title' }"
              @click="changeSort('title', '按文件名称')"
              >按文件名称
              <tui-icon
                name="todown"
                size="17"
                unit="px"
                class="l"
                :color="searchForm.sort == 'title' ? '#198fff' : ''"
                v-show="
                  searchForm.order == 'desc' && searchForm.sort == 'title'
                "
              />
              <tui-icon
                name="top"
                size="16"
                unit="px"
                class="l"
                :color="searchForm.sort == 'title' ? '#198fff' : ''"
                v-show="searchForm.order == 'asc' && searchForm.sort == 'title'"
              />
            </tui-list-cell>
          </tui-list-view>
        </view>
      </tui-bottom-popup>
      <!-- upload -->
      <tui-bottom-popup
        :show="showUpload"
        :zIndex="9999"
        :maskZIndex="9998"
        :radius="true"
        @close="showUpload = false"
      >
        <view class="upload-content">
          <view class="upload">
            <view class="item" @click="upload(0)">
              <image src="@/static/app/图片.png" class="icon" />
              <text class="txt">上传图片</text>
            </view>
            <view class="item" @click="upload(1)">
              <image src="@/static/app/视频.png" class="icon" />
              <text class="txt">上传视频</text>
            </view>
            <view class="item" @click="upload(2)">
              <image src="@/static/app/文件.png" class="icon" />
              <text class="txt">上传文件</text>
            </view>
            <view class="item" @click="upload(3)">
              <image src="@/static/app/上传文件.png" class="icon" />
              <text class="txt">新建文件夹</text>
            </view>
          </view>
        </view>
      </tui-bottom-popup>

      <!-- list -->
      <uni-swipe-action v-if="listView && !isInit">
        <uni-swipe-action-item
          v-for="(item, index) in data"
          :right-options="actions"
          :key="index"
          @click="handleAction($event, index)"
          @change="swipeChange"
        >
          <view class="file-list-item" @click="preview(item)">
            <view class="icon">
              <image mode="aspectFill" class="img" :src="getIcon(item)" />
            </view>
            <view class="detail">
              <view class="title-top">
                <view
                  :class="
                    (item.isCollect ? 'title-collect' : '') + ' title ellipsis'
                  "
                  >{{ item.title }}</view
                ><tui-icon
                  v-if="item.isCollect"
                  name="star-fill"
                  :size="17"
                  color="#ffd214"
                  class="collect-icon"
                ></tui-icon>
              </view>
              <view class="desc"
                ><text>{{ item.updateTime }}</text
                ><text class="size" v-if="!item.isFolder">{{
                  getFileSize(item.size)
                }}</text></view
              >
            </view>
          </view>
        </uni-swipe-action-item>
      </uni-swipe-action>
      <view v-if="!listView && !isInit" class="table-view">
        <uni-row :gutter="16">
          <uni-col
            :xs="12"
            :sm="8"
            :md="6"
            :lg="6"
            :xl="6"
            v-for="(item, index) in data"
            :key="index"
          >
            <view class="file-item">
              <view v-if="item.isCollect" class="collect-icon">
                <tui-icon
                  name="star-fill"
                  :size="15"
                  color="#ffd214"
                ></tui-icon>
              </view>
              <view
                class="preview"
                @click="preview(item)"
                v-if="item.type && item.type.indexOf('image') >= 0"
              >
                <image mode="aspectFill" class="preview-img" :src="item.url" />
              </view>
              <view class="preview-icon" v-else @click="preview(item)">
                <image class="preview-img" :src="getIcon(item)" />
              </view>
              <view class="info">
                <image
                  class="icon"
                  :src="getIcon(item, true)"
                  @click="preview(item)"
                />
                <view class="title" @click="preview(item)">{{
                  item.title
                }}</view>
                <tui-icon
                  @click="clickMore(item, index)"
                  name="ellipsis"
                  color="#666"
                  size="16"
                  class="more"
                />
              </view>
            </view>
          </uni-col>
        </uni-row>
      </view>

      <!-- loadmore -->
      <tui-loadmore v-show="loading" style="margin-top: 20px" />

      <!-- loading -->
      <xboot-skeleton v-if="isInit"></xboot-skeleton>

      <!-- nodata -->
      <tui-no-data
        v-if="!isInit && data.length == 0"
        imgUrl="/static/icon/no-data.png"
        :imgWidth="152"
        :imgHeight="138"
        btnText="创建文档"
        @click="showUpload = true"
        >还没有创建文档，不妨试试</tui-no-data
      >
    </view>

    <!-- 添加文件夹 -->
    <tui-modal :show="folderModal" radius="6px" padding="20px" custom fadeIn>
      <view class="folder-modal">
        <view class="folder-title">文件夹</view>
        <tui-input
          placeholder="请输入文件夹名称"
          padding="8px 0"
          :maxlength="50"
          :lineLeft="false"
          class="folder-input"
          v-model="categoryTitle"
          :adjustPosition="false"
          clearable
        >
        </tui-input>
        <view class="btns">
          <tui-button
            type="white"
            height="40px"
            @click="folderModal = false"
            class="r"
            >取消</tui-button
          ><tui-button
            :disabled="!categoryTitle"
            height="40px"
            @click="addFolder"
            >创建</tui-button
          >
        </view>
      </view>
    </tui-modal>

    <!-- 重命名 -->
    <tui-modal :show="renameModal" radius="6px" padding="20px" custom fadeIn>
      <view class="folder-modal">
        <view class="folder-title">重命名</view>
        <tui-input
          placeholder="请输入名称"
          padding="8px 0"
          :maxlength="50"
          :lineLeft="false"
          class="folder-input"
          v-model="renameForm.newTitle"
          :adjustPosition="false"
          clearable
        >
        </tui-input>
        <view class="btns">
          <tui-button
            type="white"
            height="40px"
            @click="renameModal = false"
            class="r"
            >取消</tui-button
          ><tui-button
            :disabled="!renameForm.newTitle"
            height="40px"
            @click="rename"
            >提交</tui-button
          >
        </view>
      </view>
    </tui-modal>
  </view>
</template>

<script>
import {
  getFileList,
  collectFile,
  renameFile,
  copyFile,
  trashFile,
  loadFileCate,
  addFileCate,
  trashFileCate,
  collectFileCate,
  renameFileCate,
  uploadFile,
} from "@/api/file.js";
import { getFileIcon } from "../file.js";
export default {
  data() {
    return {
      addBtnBottom: 50,
      title: "",
      openFilter: false,
      listView: true,
      showSort: false,
      showFilter: false,
      sortTitle: "按修改时间",
      listView: true,
      showUpload: false,
      searchForm: {
        pageNumber: 1, // 当前页数
        pageSize: 10, // 页面大小
        sort: "updateTime",
        order: "desc",
        categoryId: "0",
        parentId: "0",
        delFlag: 0,
        type: "",
        isCollect: "",
      },
      actions: [
        {
          text: "更多",
          style: {
            backgroundColor: "#c5c8ce",
            fontsize: "15px",
          },
        },
        {
          text: "分享",
          style: {
            backgroundColor: "#c5c8ce",
            fontsize: "15px",
          },
        },
        {
          text: "删除",
          style: {
            backgroundColor: "#ed4014",
            fontsize: "15px",
          },
        },
      ],
      data: [],
      result: {},
      isInit: true,
      loading: false,
      currData: null,
      hasOpen: false,
      folderModal: false,
      renameModal: false,
      renameForm: {
        id: "",
        newTitle: "",
      },
      categoryTitle: "",
    };
  },
  onPullDownRefresh() {
    this.getDataList();
  },
  onLoad(options) {
    if (options.title) {
      this.title = options.title;
    }
    if (options.parentId) {
      this.searchForm.parentId = options.parentId;
      this.searchForm.categoryId = options.parentId;
    }
    if (options.type) {
      this.searchForm.type = options.type;
    }
    if (options.isCollect) {
      this.searchForm.isCollect = true;
    }
    this.init();
  },
  onReachBottom() {
    this.loadMore();
  },
  methods: {
    init() {
      this.getDataList();
    },
    back() {
      uni.navigateBack({
        delta: 1,
      });
    },
    getDataList() {
      // 先加载分类文件夹
      loadFileCate(this.searchForm)
        .then((res) => {
          if (res.success) {
            this.data = res.result;
            this.data.forEach((e) => {
              e.isFolder = true;
            });
            // 再加载该类别文件
            this.searchForm.pageNumber = 1;
            getFileList(this.searchForm).then((res) => {
              this.isInit = false;
              uni.stopPullDownRefresh();
              if (res.success) {
                this.result = res.result;
                this.data = this.data.concat(res.result.content);
                this.data.forEach((e) => {
                  e.updateTime = e.updateTime.substring(
                    0,
                    e.updateTime.length - 3
                  );
                });
              }
            });
          } else {
            this.isInit = false;
            uni.stopPullDownRefresh();
          }
        })
        .catch((e) => {
          this.isInit = false;
          uni.stopPullDownRefresh();
        });
    },
    loadMore() {
      if (this.result.last || this.isInit) {
        return;
      }
      this.searchForm.pageNumber++;
      this.loading = true;
      getFileList(this.searchForm).then((res) => {
        uni.stopPullDownRefresh();
        this.loading = false;
        if (res.success) {
          this.result = res.result;
          this.data = this.data.concat(res.result.content);
        }
      });
    },
    getIcon(v, isImgIcon) {
      return getFileIcon(v, isImgIcon);
    },
    handleView() {
      this.listView = !this.listView;
    },
    changeSort(v, title) {
      if (v == this.searchForm.sort) {
        // 相同 仅改变order
        if (this.searchForm.order == "desc") {
          this.searchForm.order = "asc";
        } else {
          this.searchForm.order = "desc";
        }
      } else {
        // 不同
        this.searchForm.sort = v;
        this.sortTitle = title;
        this.searchForm.order = "desc";
      }
      this.showSort = false;
      this.getDataList();
    },
    swipeChange(v) {
      setTimeout(() => {
        if (v == "none") {
          this.hasOpen = false;
        } else {
          this.hasOpen = true;
        }
      }, 300);
    },
    handleAction(v, index) {
      this.currData = this.data[index];
      this.currData.index = index;
      if (v.index == "0") {
        setTimeout(() => {
          if (this.currData.isFolder) {
            uni.showActionSheet({
              title: this.currData.title,
              itemList: [
                "重命名",
                this.currData.isCollect ? "取消收藏" : "收藏",
              ],
              success: (res) => {
                if (res.tapIndex == "0") {
                  this.renameForm.id = this.currData.id;
                  this.renameForm.newTitle = this.currData.title;
                  this.renameModal = true;
                } else if (res.tapIndex == "1") {
                  this.collect();
                }
              },
            });
          } else {
            uni.showActionSheet({
              title: this.currData.title,
              itemList: [
                "复制链接",
                "重命名",
                "创建副本",
                this.currData.isCollect ? "取消收藏" : "收藏",
                "保存到本地",
              ],
              success: (res) => {
                if (res.tapIndex == "0") {
                  uni.setClipboardData({
                    data: this.currData.url,
                    success: () => {
                      this.msg("文件链接已复制");
                    },
                  });
                } else if (res.tapIndex == "1") {
                  this.renameForm.id = this.currData.id;
                  this.renameForm.newTitle = this.currData.title;
                  this.renameModal = true;
                } else if (res.tapIndex == "2") {
                  this.copy();
                } else if (res.tapIndex == "3") {
                  this.collect();
                } else if (res.tapIndex == "4") {
                  this.download();
                }
              },
            });
          }
        }, 20);
      } else if (v.index == "1") {
        if (this.currData.isFolder) {
          uni.setClipboardData({
            data: this.currData.title,
            success: () => {
              this.msg("文件夹名已复制");
            },
          });
        } else {
          // #ifdef H5
          uni.setClipboardData({
            data: this.currData.url,
            success: () => {
              this.msg("文件分享链接已复制");
            },
          });
          // #endif
          // #ifndef H5
          uni.shareWithSystem({
            summary: this.currData.title,
            href: this.currData.url,
            success() {
              // 分享完成，请注意此时不一定是成功分享
            },
            fail() {
              // 分享失败
            },
          });
          // #endif
        }
      } else if (v.index == "2") {
        this.delete();
      }
    },
    clickMore(v, index) {
      this.currData = v;
      this.currData.index = index;
      if (this.currData.isFolder) {
        uni.showActionSheet({
          title: this.currData.title,
          itemList: [
            "重命名",
            this.currData.isCollect ? "取消收藏" : "收藏",
            "删除",
          ],
          success: (res) => {
            if (res.tapIndex == "0") {
              this.renameForm.id = this.currData.id;
              this.renameForm.newTitle = this.currData.title;
              this.renameModal = true;
            } else if (res.tapIndex == "1") {
              this.collect();
            } else if (res.tapIndex == "2") {
              this.delete();
            }
          },
        });
      } else {
        uni.showActionSheet({
          title: this.currData.title,
          itemList: [
            "复制链接",
            "重命名",
            "创建副本",
            this.currData.isCollect ? "取消收藏" : "收藏",
            "保存到本地",
            "删除",
          ],
          success: (res) => {
            if (res.tapIndex == "0") {
              uni.setClipboardData({
                data: this.currData.url,
                success: () => {
                  this.msg("文件链接已复制");
                },
              });
            } else if (res.tapIndex == "1") {
              this.renameForm.id = this.currData.id;
              this.renameForm.newTitle = this.currData.title;
              this.renameModal = true;
            } else if (res.tapIndex == "2") {
              this.copy();
            } else if (res.tapIndex == "3") {
              this.collect();
            } else if (res.tapIndex == "4") {
              this.download();
            } else if (res.tapIndex == "5") {
              this.delete();
            }
          },
        });
      }
    },
    preview(v) {
      if (this.hasOpen) {
        return;
      }
      if (v.isFolder) {
        uni.navigateTo({
          url:
            "/pages/file/list/list?title=" +
            v.title +
            "&parentId=" +
            v.id +
            "&type=" +
            this.searchForm.type +
            "&isCollect=" +
            this.searchForm.isCollect,
        });
        return;
      }
      this.showLoading();
      uni.downloadFile({
        url: v.url,
        success: (res) => {
          let filePath = res.tempFilePath;
          uni.openDocument({
            filePath: filePath,
            showMenu: true,
          });
        },
        complete: () => {
          uni.hideLoading();
        },
      });
    },
    upload(v) {
      this.showUpload = false;
      if (v == 0) {
        uni.chooseImage({
          count: 9,
          sizeType: ["original", "compressed"],
          sourceType: ["album"],
          success: (res) => {
            this.msg("已加入上传队列");
            res.tempFilePaths.forEach((e) => {
              this.submitUpload(e);
            });
          },
        });
      } else if (v == 1) {
        uni.chooseVideo({
          sourceType: ["album"],
          success: (res) => {
            this.msg("已加入上传队列");
            this.submitUpload(res.tempFilePath);
          },
        });
      } else if (v == 2) {
        // #ifdef H5
        uni.chooseFile({
          success: (res) => {
            this.msg("已加入上传队列");
            res.tempFilePaths.forEach((e) => {
              this.submitUpload(e);
            });
          },
        });
        // #endif
        // #ifndef H5
        uni.chooseImage({
          count: 9,
          sizeType: ["original", "compressed"],
          sourceType: ["camera", "album"],
          success: (res) => {
            this.msg("已加入上传队列");
            res.tempFilePaths.forEach((e) => {
              this.submitUpload(e);
            });
          },
        });
        // #endif
      } else if (v == 3) {
        this.categoryTitle = "";
        this.folderModal = true;
      }
    },
    submitUpload(filePath) {
      uni.uploadFile({
        url: uploadFile,
        filePath: filePath,
        name: "file",
        header: {
          accessToken: this.getToken(),
        },
        formData: {
          categoryId: this.searchForm.categoryId,
        },
        success: (res) => {
          res = JSON.parse(res.data);
          if (res.success) {
            this.msg("上传成功");
            this.getDataList();
          } else {
            this.msg(res.message);
          }
        },
      });
    },
    trash() {
      this.showLoading();
      if (!this.currData.isFolder) {
        trashFile({ ids: this.currData.id }).then((res) => {
          uni.hideLoading();
          if (res.success) {
            this.data.splice(this.currData.index, 1);
            this.msg("操作成功");
          }
        });
      } else {
        trashFileCate({ id: this.currData.id }).then((res) => {
          uni.hideLoading();
          if (res.success) {
            this.data.splice(this.currData.index, 1);
            this.msg("操作成功");
          }
        });
      }
    },
    delete() {
      uni.showModal({
        title: this.currData.isFolder ? "确定删除此文件夹" : "确定删除此文件",
        content: "7天内可在回收站中找回已删文件",
        success: (res) => {
          if (res.confirm) {
            this.showLoading();
            if (!this.currData.isFolder) {
              trashFile({ ids: this.currData.id }).then((res) => {
                uni.hideLoading();
                if (res.success) {
                  this.data.splice(this.currData.index, 1);
                  this.msg("操作成功");
                }
              });
            } else {
              trashFileCate({ id: this.currData.id }).then((res) => {
                uni.hideLoading();
                if (res.success) {
                  this.data.splice(this.currData.index, 1);
                  this.msg("操作成功");
                }
              });
            }
          }
        },
      });
    },
    rename() {
      this.renameModal = false;
      this.showLoading();
      uni.hideLoading();
      if (!this.currData.isFolder) {
        renameFile(this.renameForm).then((res) => {
          uni.hideLoading();
          if (res.success) {
            this.getDataList();
            this.msg("操作成功");
          }
        });
      } else {
        renameFileCate(this.renameForm).then((res) => {
          uni.hideLoading();
          if (res.success) {
            this.getDataList();
            this.msg("操作成功");
          }
        });
      }
    },
    copy() {
      this.showLoading({ mask: false });
      copyFile({ id: this.currData.id }).then((res) => {
        uni.hideLoading();
        if (res.success) {
          this.getDataList();
          this.msg("操作成功");
        }
      });
    },
    collect() {
      if (!this.currData.isFolder) {
        collectFile({ id: this.currData.id }).then((res) => {
          if (res.success) {
            this.data[this.currData.index].isCollect =
              !this.data[this.currData.index].isCollect;
            this.msg("操作成功");
          }
        });
      } else {
        collectFileCate({ id: this.currData.id }).then((res) => {
          if (res.success) {
            this.data[this.currData.index].isCollect =
              !this.data[this.currData.index].isCollect;
            this.msg("操作成功");
          }
        });
      }
    },
    download() {
      let v = this.currData;
      if (v.type.indexOf("image") >= 0) {
        this.showLoading();
        uni.downloadFile({
          url: v.url,
          success: (res) => {
            let filePath = res.tempFilePath;
            uni.saveImageToPhotosAlbum({
              filePath: filePath,
              success: () => {
                this.msg("保存至本地相册成功");
              },
              complete: () => {
                uni.hideLoading();
              },
            });
          },
        });
      } else if (v.type.indexOf("video") >= 0) {
        this.showLoading();
        uni.downloadFile({
          url: v.url,
          success: (res) => {
            let filePath = res.tempFilePath;
            uni.saveVideoToPhotosAlbum({
              filePath: filePath,
              success: () => {
                this.msg("保存至本地相册成功");
              },
              complete: (res) => {
                console.log(res);
                uni.hideLoading();
              },
            });
          },
        });
      } else {
        this.preview(v);
      }
    },
    addFolder() {
      this.folderModal = false;
      this.showLoading();
      let params = {
        title: this.categoryTitle,
        parentId: this.searchForm.categoryId,
        sortOrder: 0,
      };
      addFileCate(params).then((res) => {
        uni.hideLoading();
        if (res.success) {
          this.getDataList();
          this.msg("操作成功");
        }
      });
    },
    toSearch() {
      uni.navigateTo({
        url: "/pages/search/search?type=2",
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "./list.scss";
</style>
